﻿using System;
using System.ComponentModel;
using System.Windows;

namespace DynamicGeometry
{
    public interface IFigureStyle : INotifyPropertyChanged
    {
        string Name { get; set; }
        Drawing Drawing { get; set; }
        Style GetWpfStyle(IFigure figure);
        FrameworkElement GetSampleGlyph();
        IFigureStyle Clone();
        void OnApplied(IFigure figure, FrameworkElement element);
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public class StyleForAttribute : Attribute
    {
        public StyleForAttribute(Type figureType)
        {
            FigureBaseType = figureType;
        }

        public Type FigureBaseType { get; set; }
    }

    public static class StyleExtensions
    {
        public static Style GetWpfStyle(this IFigureStyle style)
        {
            return style.GetWpfStyle(null);
        }

        public static bool SupportsFigureType(this Type styleType, Type figureType)
        {
            var attributes = styleType.GetAttributes<StyleForAttribute>();
            foreach (var attribute in attributes)
            {
                if (attribute.FigureBaseType.IsAssignableFrom(figureType))
                {
                    return true;
                }
            }
            return false;
        }

        public static void Apply(this FrameworkElement element, Style style)
        {
            if (style == null)
            {
                return;
            }
            foreach (Setter setter in style.Setters)
            {
                element.ClearValue(setter.Property);
            }
            element.Style = style;
        }

        public static void Apply(this IFigure figure, FrameworkElement element, IFigureStyle figureStyle)
        {
            var wpfStyle = figureStyle.GetWpfStyle(figure);
            element.Apply(wpfStyle);
            figureStyle.OnApplied(figure, element);
        }
    }
}